package com.jic.order.impl;

import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.order.entity.*;
import com.jic.order.enums.AfterSaleStatusEnum;
import com.jic.order.manage.request.OrderReturnGoodRecordRequest;
import com.jic.order.mapper.OrderAfterSaleApplyMapper;
import com.jic.order.mapper.OrderMapper;
import com.jic.order.request.OrderAfterSaleApplyBatchRequest;
import com.jic.order.service.OrderAfterSaleApplyService;
import com.jic.order.service.OrderBaleDeliveryService;
import com.jic.order.service.OrderReturnGoodRecordService;
import com.jic.order.utils.SerialNoUtil;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.store.request.MStoreFrozenRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单售后申请 服务类
 *
 * @author xuyongliang
 * @since 2020-02-01
 */
@Service
@Slf4j
public class OrderAfterSaleApplyServiceImpl implements OrderAfterSaleApplyService {

	@Autowired
	private OrderAfterSaleApplyMapper modelMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderBaleDeliveryService orderBaleDeliveryService;
	@Autowired
	private OrderReturnGoodRecordService orderReturnGoodRecordService;
	@Resource
	ProductListApi productListApi;

	@Override
	public Integer orderAfterSaleApplyAdd(OrderAfterSaleApplyModel modelEntity) {
		return modelMapper.orderAfterSaleApplyAdd(modelEntity);
	}

	@Override
	public RestResult<String> orderAfterSaleApplyBatchAdd(OrderAfterSaleApplyBatchRequest modelEntity) {
		OrderAfterSaleApplyModel model = new OrderAfterSaleApplyModel();
		BeanUtils.copyProperties(modelEntity, model);

		for (int i = 0; i < modelEntity.getGoodsIdList().size(); i++) {
			model.setAfterSaleNo(SerialNoUtil.genAfterSaleNo());
			model.setStatus(1010);
			model.setApplyReason(modelEntity.getApplyReason());
			model.setApplyTime(new Date());
			model.setGoodsId(modelEntity.getGoodsIdList().get(i));
			model.setProofPics(modelEntity.getProofPics());
			model.setLogisticsCompany(modelEntity.getLogisticsCompany());
			model.setLogisticsNo(modelEntity.getLogisticsNo());
			modelMapper.orderAfterSaleApplyAdd(model);
		}
		return RestResult.success("售后申请成功");
	}

	@Override
	public RestResult<String> orderAfterSaleUpdate(OrderAfterSaleApplyBatchRequest modelEntity) {
		if (modelEntity.getStatus() == 1030 || modelEntity.getStatus() == 1040) {
			modelEntity.setAuditTime(new Date());
		}
		Integer saleUpdate = modelMapper.orderAfterSaleUpdate(modelEntity);
		if (saleUpdate < 0) {
			return RestResult.success("订单售后修改失败");
		}
		return RestResult.success("订单售后修改成功");
	}



    @Override
	public Integer orderAfterSaleApplyEdit(OrderAfterSaleApplyModel modifyEntity, OrderAfterSaleApplyModel whereCondition) {
		return modelMapper.orderAfterSaleApplyEdit(modifyEntity, whereCondition);
	}

	@Override
	public Integer orderAfterSaleApplyDelete(Map map) {
		return modelMapper.orderAfterSaleApplyDelete(map);
	}

	@Override
	public OrderAfterSaleApplyModel orderAfterSaleApplyQuery(Map map) {
		return modelMapper.orderAfterSaleApplyQuery(map);
	}


	@Override
	public PageResult<OrderAfterSaleApplyModel> orderAfterSaleApplyQueryPageList(OrderAfterSaleApplyModel modelEntity, Page pageQuery) {
		//计算下标
		int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
		List<OrderAfterSaleApplyModel> list = modelMapper.orderAfterSaleApplyQueryPageList(startIndex, pageQuery.getLimit(), modelEntity);
		if (CollectionUtils.isNotEmpty(list)) {
			list.forEach(x -> {
				/**
				 * @Description: 
				 * @Param: [modelEntity, pageQuery]
				 * @return: com.jic.common.base.vo.PageResult<com.jic.order.entity.OrderAfterSaleApplyModel>
				 * @Author: wulei
				 * @Date: 2020/12/9 修改bug
				 * 在正常逻辑中，一个售后服务对应的订单号只存在唯一一张 此处这样写 避免帐数据
				 */
				//TODO  优化接口
				Order order = new Order();
				order.setOrderNo(x.getOrderNo());
				List<Order> query = orderMapper.query(order);
				if (order != null&&query.size()>0) {
					x.setMerchantName(query.get(0).getMerchantName());
					x.setStoreName(query.get(0).getStoreName());
				}
			});
		}
		long count = modelMapper.orderAfterSaleApplyQueryPageCount(modelEntity);
		PageResult pageResult = new PageResult();
		pageResult.setRows(list);
		pageResult.setTotal(count);
		return pageResult;
	}

	@Override
	public Integer orderAfterSaleApplyQueryStatusListCount(Long memberId) {
		//组装售后状态
		List<Integer> statusList = stayAfterSaleCount();
		// 查询数量
		Integer count = modelMapper.orderAfterSaleApplyQueryStatusListCount(memberId, statusList);
		return count;
	}

	private List<Integer> stayAfterSaleCount() {
		List<Integer> statusList = new ArrayList<>(8);

		Integer statusAppRefund = AfterSaleStatusEnum.APP_REFUND.getCode();
		Integer statusAuditPass = AfterSaleStatusEnum.AUDIT_PASS.getCode();
		Integer statusRefunding = AfterSaleStatusEnum.REFUNDING.getCode();

		statusList.add(statusAppRefund);
		statusList.add(statusAuditPass);
		statusList.add(statusRefunding);
		return statusList;
	}

	@Override
	public Integer orderAfterSaleApplyChangeStatus(Map map) {
		return modelMapper.orderAfterSaleApplyChangeStatus(map);
	}

	@Override
	public Integer orderAfterSaleApplyChangeApproveStatus(Map map) {
		return modelMapper.orderAfterSaleApplyChangeApproveStatus(map);
	}

	@Override
	public RestResult exchangeGoods(OrderAfterSaleApplyBatchRequest modelEntity) {
		try {
			log.info("开始进入订单售后退换========>" + modelEntity.toString());
			modelMapper.orderAfterSaleUpdate(modelEntity);
			//如果是换货已发货  插入一条物流信息和插入一条退货记录并更新库存
			if (modelEntity.getStatus() == 1100) {
				//默认插入一条物流信息
				OrderBaleDelivery orderBaleDelivery = new OrderBaleDelivery();
				orderBaleDelivery.setExpressNo(modelEntity.getLogisticsNo());
				List<OrderBaleDelivery> orderBaleDeliveryList = orderBaleDeliveryService.query(orderBaleDelivery);
				if (CollectionUtils.isEmpty(orderBaleDeliveryList)) {
					orderBaleDelivery.setOrderNo(modelEntity.getOrderNo());
					orderBaleDelivery.setDeliveryCompanyId(Long.valueOf(modelEntity.getLogisticsCompany()));
					//物流备注暂时写死
					orderBaleDelivery.setRemark("【北京市】 快件已在 【北京太阳宫】 签收, 签收人: 前台, 如有疑问请电联:13370150897 / 010-67443169, 您的快递已经妥投。风里来雨里去, 只为客官您满意。上有老下有小, 赏个好评好不好？【请在评价快递员处帮忙点亮五颗星星哦~】");
					orderBaleDeliveryService.insert(orderBaleDelivery);
				}
				//插入退货记录并且更新库库存
				if (CollectionUtils.isNotEmpty(modelEntity.getOrderReturnGoodRecordRequestList())) {
					for (OrderReturnGoodRecordRequest orderReturnGoodRecordRequest : modelEntity.getOrderReturnGoodRecordRequestList()) {
						OrderReturnGoodRecord orderReturnGoodRecord = new OrderReturnGoodRecord();
						orderReturnGoodRecord.setAfterSaleId(modelEntity.getId());
						orderReturnGoodRecord.setAfterSaleNo(modelEntity.getAfterSaleNo());
						orderReturnGoodRecord.setGoodsId(orderReturnGoodRecordRequest.getGoodsId());
						orderReturnGoodRecord.setGoodsNum(orderReturnGoodRecordRequest.getGoodsNum());
						orderReturnGoodRecordService.insert(orderReturnGoodRecord);
						MStoreFrozenRequest mStoreFrozenRequest = new MStoreFrozenRequest();
						mStoreFrozenRequest.setOrderId(modelEntity.getId());
						mStoreFrozenRequest.setApplyNum(Long.valueOf(orderReturnGoodRecordRequest.getGoodsNum()));
						mStoreFrozenRequest.setProductId(orderReturnGoodRecordRequest.getGoodsId());
						productListApi.frozenStock(mStoreFrozenRequest);
					}
				}

			}
			return RestResult.success(true);
		} catch (Exception e) {
			log.error("订单售后退换========>" + e.getLocalizedMessage());
			return RestResult.error("9999", e.getLocalizedMessage());
		}
	}

    @Override
    public PageResult<OrderAfterSaleApplyModel> queryPage(OrderAfterSaleApplyModel orderAfterSaleApplyModel, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<OrderAfterSaleApplyModel> list = modelMapper.queryPage(startIndex, pageQuery.getLimit(), orderAfterSaleApplyModel);
        long count = modelMapper.queryPageCount(orderAfterSaleApplyModel);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }
}